// websocketService.js
import SockJS from 'sockjs-client/dist/sockjs.min.js';
import Stomp from 'stompjs';

const socket = new SockJS('http://localhost:8080/ws'); // 后端WebSocket端点
const stompClient = Stomp.over(socket);

export const connect = (callback, sessionId) => {
    stompClient.connect({}, frame => {
        console.log('Connected: ' + frame);
        // 订阅普通消息
        stompClient.subscribe('/topic/messages', (message) => {
            callback(JSON.parse(message.body));
        });
        // 订阅交互式命令的消息
        if (sessionId) {
            stompClient.subscribe('/topic/interactive/' + sessionId, (message) => {
                const data = JSON.parse(message.body);
                // 确保交互式消息有正确的类型
                data.type = 'interactive';
                callback(data);
            });
        }
    }, onError);
};
const onError = (error) => {
    console.error('WebSocket 连接错误:', error);
    // 可以在这里添加重连逻辑
    if (error.headers && error.headers.message) {
        console.error('错误详情:', error.headers.message);
    }
};
export const sendMessage = (message) => {
    console.log("sendMessage", JSON.stringify(message));
    // 确保消息有正确的类型
    if (!message.type) {
        message.type = 'command';
    }
    stompClient.send("/app/sendMessage", {}, JSON.stringify(message));
};
export const disconnect = () => {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    console.log("Disconnected");
};